import socket
import threading
import time
import random
from net.protocol.cmd import command

packet=lambda cmd,content:command().packet(cmd,content)
unpacket=lambda buff:command().unpacket(buff)

class ClientProcess(threading.Thread): 
    def __init__(self,uri,port,clientname):
        '''
        init client process service
        '''
        threading.Thread.__init__(self)
        self._flag=threading.Event()
        self._flag.set()
        self._runing=threading.Event()
        self._runing.set()
        self.__name = clientname
        self.__status=False            #local work thread status
        self.socket = None              #local socket
        self.uri = uri            #remote ip address
        self.port = port
        self.classname=None             #request process
        self.namespace=None             #request namespace
        self.method=None                #request process runtime method
        
    def run(self):
        '''while True:
            print("%d\r\n" % (random.randint(1, 10000)))
        ''' 
        print('Client - client will start!') 
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
        self.__connect__()
        self.joinnetwork()
        

    def clientCmd(self):
        '''cmd=input("\r\nplease input cmd:")
        if cmd.lower() == "join":
            self.join()
        if cmd.lower() == "exit":
            self.exit()
        '''

    def __connect__(self):
        '''
        connect server
        '''
        try:
            if self.uri and self.port:
                self.socket.connect((self.uri,self.port))
            else:
                print("Client - uri or port is null,%s,%s"%(self.uri,self.port))
        except Exception as e:
            print("Client - join is error:%s"%e)

    def __send__(self,buff):
        if buff:
            self.socket.send(buff)
        else:
            print("Client - error:buff is none")

    def __recv__(self):
        buff=bytearray()
        while True:
            recv=self.socket.recv(1024)
            buff.extend(recv)
            if len(recv)>0:
                if recv[len(recv)-1]==0x00:
                    self.eventroute(buff)
                    buff.clear()
                    continue
    

    def eventroute(self,buff):
        dataStr=command().unpacket(buff,"utf-8")
        if dataStr.cmd.lower() == "join":
            self.joinnetwork()
        elif dataStr.cmd.lower() == "work":
            self.work(dataStr.content)
        elif dataStr.cmd.lower() == "response":
            self.response(dataStr.content)
        elif dataStr.cmd.lower() == "online":
            self.online()
        else:
            self.response(dataStr.content)
        
    def joinnetwork(self):
        '''
            client will be join the work network and set status free
        '''
        if not self.__status:
            jointry=1
            while not self.__status:
                print("Client - Client(%s) try join network %d" % (self.__name,jointry))
                self.__send__(command().packet("join",self.__name))
                self.__recv__()
                time.sleep(5)
                jointry=jointry+1
                continue
            return True;
        else:
            return True;

    def online(self):
        self.__status=True
        print("Client - Client(%s) join success" % self.__name)

    def notifyServerStatus(self,content):
        self.__send__(command().packet("setstatus",content))

    def work(self,content):
        self.notifyServerStatus("working")
        print("Client - server notify to client work content:\r\n %s" % content)
        '''
            todo work
        '''
        self.complete()
        return True

    def complete(self):
        '''
            work has completed notify to server
        '''
        self.__send__(command().packet("complete","00001"))

    def exit():
        '''
            client weill be exit the network,if the client has an work not complete must notify to server
        '''
        self.__send__(command().packet("exit","000093"))
        return True

    def response(self,content):
        '''
            Serve Notify Message
        '''
        print("Client - Server send : %s" % content)

    def heartpackage():
        self.__send__(command().packet("heartpackage",""))
        return True